import { _decorator, Node } from 'cc';
import { ecs } from 'db://app-game/libs/ecs/ECS';
import { CCComp } from 'db://app-game/module/common/CCComp';
import { Role } from '../Role';
import { RoleViewLoader } from './RoleViewLoader';
import { RoleViewLowerBodyAnimator } from './RoleViewLowerBodyAnimator';
import { RoleViewUpperBodyAnimator } from './RoleViewUpperBodyAnimator';
import { RoleModelComp } from '../model/RoleModelComp';

const { ccclass, property } = _decorator;

/** 角色显示组件 */
@ccclass('RoleViewComp') // 定义为 Cocos Creator 组件
@ecs.register('RoleView', false) // 定义为 ECS 组件
export class RoleViewComp extends CCComp {
  /** 角色身体 */
  body: Node = null!;
  /** 角色上半身 */
  upperBody: Node = null!;
  /** 角色下半身 */
  lowerBody: Node = null!;

  /** 角色动画资源管理 */
  loader: RoleViewLoader = null!;
  /** 角色上半身动画规则管理 */
  upperBodyAnimator: RoleViewUpperBodyAnimator = null!;
  /** 角色上半身动画规则管理 */
  lowerBodyAnimator: RoleViewLowerBodyAnimator = null!;

  protected onLoad(): void {
    let role = this.ent as Role;

    // 1.获取节点
    this.body = this.node.getChildByName('body');
    this.upperBody = this.body.getChildByName('upper-body');
    this.lowerBody = this.body.getChildByName('lower-body');

    // 2. 加载角色资源
    this.loader = this.node.addComponent(RoleViewLoader);
    this.node.emit('load', role);

    // 3. 获取动画组件并设置角色引用
    this.upperBodyAnimator = this.upperBody.addComponent(RoleViewUpperBodyAnimator)!;
    this.upperBodyAnimator.role = role;
    this.lowerBodyAnimator = this.lowerBody.addComponent(RoleViewLowerBodyAnimator)!;
    this.lowerBodyAnimator.role = role;

    role.roleIdle();
  }

  update() {
    const a = this.ent.get(RoleModelComp);
    if (a.chp <= 0) {
      a.chp = 100;
    } else {
      a.chp -= 1;
    }
  }

  reset(ent: ecs.Entity): void {
    this.node.destroy();
  }
}
